package com.genesis.web.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.genesis.mall.common.Result;
import com.genesis.mall.dto.AdminRoleDto;
import com.genesis.mall.dto.PageDto;
import com.genesis.mall.entity.*;
import com.genesis.mall.service.*;
import com.genesis.mall.utils.TokenUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 后台用户表 前端控制器
 * </p>
 *
 * @author author
 * @since 2022-08-01
 */
@Slf4j
@RestController
@RequestMapping("/admin")
public class UmsAdminController {

    @Autowired
    private IUmsAdminService umsAdminService;

    @Autowired
    private IUmsAdminRoleRelationService umsAdminRoleRelationService;

    @Autowired
    private IUmsRoleService umsRoleService;

    @Autowired
    private IUmsRoleMenuRelationService umsRoleMenuRelationService;

    @Autowired
    private IUmsMenuService umsMenuService;





    @PostMapping("/login")
    public Result<Map<String, String>> login(@RequestBody UmsAdmin umsAdmin) {
        String token = umsAdminService.login(umsAdmin.getUsername(), umsAdmin.getPassword());
        Map<String, String> resMap = new HashMap<>();
        resMap.put("token", token);
        resMap.put("tokenHead", "Bearer ");
        return Result.success(resMap);
    }

    /**
     * 获取当前登录用户的信息
     *
     */
    @GetMapping("/info")
    public Result<Map<String, Object>> info(HttpServletRequest request) {
        String tokenHeader = request.getHeader("Authorization");
        String token = tokenHeader.split(" ")[1];
        log.info(token);
        Claims claims = TokenUtil.getClaims(token);
        Integer adminId = (Integer) claims.get("adminId");
        HashMap<String, Object> resMap = new HashMap<>();
        //查询当前用户的roles
        LambdaQueryWrapper<UmsAdminRoleRelation> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UmsAdminRoleRelation::getAdminId, adminId);
        List<UmsAdminRoleRelation> adminRoleRelations = umsAdminRoleRelationService.list(lqw);
        List<String> roles = adminRoleRelations.stream().map(adminRoleRelation -> {
            UmsRole umsRole = umsRoleService.findById(adminRoleRelation);
            return umsRole.getName();
        }).collect(Collectors.toList());
        resMap.put("roles", roles);
        //查询当前用户的icon
        UmsAdmin umsAdmin = umsAdminService.getById(adminId);
        resMap.put("icon", umsAdmin.getIcon());
        resMap.put("username", umsAdmin.getUsername());
        //查询当前用户的menus
        List<Long> roleId = adminRoleRelations.stream().map(UmsAdminRoleRelation::getRoleId).collect(Collectors.toList());
        LambdaQueryWrapper<UmsRoleMenuRelation> roleMenuLqw = new LambdaQueryWrapper<>();
        if (roleId.contains(5L)) {
            roleMenuLqw.eq(UmsRoleMenuRelation::getRoleId, 5L);
        } else {
            for (Long id : roleId) {
                roleMenuLqw.or().eq(UmsRoleMenuRelation::getRoleId, id);
            }
        }
        List<UmsRoleMenuRelation> umsRoleMenuRelations = umsRoleMenuRelationService.list(roleMenuLqw);
        List<UmsMenu> menus = umsRoleMenuRelations.stream().map(umsRoleMenuRelation -> {
            return umsMenuService.getById(umsRoleMenuRelation.getMenuId());
        }).collect(Collectors.toList());
        resMap.put("menus", menus);
        return Result.success(resMap);

    }

    /**
     * 获取用户分页信息
     */
    @GetMapping("/list")
    public Result<PageDto<UmsAdmin>> adminList(PageDto<UmsAdmin> pageDto) {
        Page<UmsAdmin> page = new Page<>(pageDto.getPageNum(), pageDto.getPageSize());
        LambdaQueryWrapper<UmsAdmin> adminLqw = new LambdaQueryWrapper<>();
        adminLqw.like(pageDto.getKeyword() != null, UmsAdmin::getUsername, pageDto.getKeyword());
        umsAdminService.page(page, adminLqw);
        log.info(String.valueOf(page.getPages()));
        pageDto.setTotalPage((int) page.getPages());
        pageDto.setTotal((int) page.getTotal());
        pageDto.setList(page.getRecords());
        return Result.success(pageDto);
    }

    /**
     * 用户注册

     */
    @PostMapping("/register")
    public Result<String> adminRegister(@RequestBody UmsAdmin umsAdmin){
        if (StringUtils.isEmpty(umsAdmin.getUsername())){
            return Result.error("用户名不能为空");
        }
        if (StringUtils.isEmpty(umsAdmin.getPassword())){
            return Result.error("密码不能为空");
        }
        //查询数据中的用户
        List<String> adminList = umsAdminService.getAdmin();
        if (!adminList.contains(umsAdmin.getUsername())) {
            umsAdmin.setCreateTime(LocalDateTime.now());
            BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
            String password = bCryptPasswordEncoder.encode(umsAdmin.getPassword());
            umsAdmin.setPassword(password);
            umsAdminService.save(umsAdmin);
            return Result.success();
        } else {
            return Result.error("用户名已存在,请重试");
        }
    }
    //删除指定用户
    @PostMapping("/delete/{id}")
    public Result<String> adminDelete(@PathVariable Long id){
        umsAdminService.removeById(id);
        return Result.success();
    }
    //获得指定用户的信息
    @GetMapping("/{id}")
    public Result<UmsAdmin> adminInfo(@PathVariable Long id){
        //根据id查询用户信息
        UmsAdmin umsAdmin = umsAdminService.getById(id);
        return Result.success(umsAdmin);
    }

    //修改用户指定用户信息
    @PostMapping("/update/{id}")
    public Result<String> updateAdmin(@RequestBody UmsAdmin umsAdmin){
        //判断密码是否和数据库中密码相等
        UmsAdmin admin = umsAdminService.getById(umsAdmin.getId());
        if (umsAdmin.getPassword().equals(admin.getPassword())){
            umsAdmin.setPassword(null);
        }else{
            String password = new BCryptPasswordEncoder().encode(umsAdmin.getPassword());
            umsAdmin.setPassword(password);
        }
        //更新数据库中的数据
        umsAdminService.updateById(umsAdmin);
        return Result.success();
    }

    /**
     * 退出登录
     */
    @PostMapping("/logout")
    public Result<String> logout(){
        return Result.success();
    }

    /**
     * 获得指定用户的角色
     */
    @GetMapping("/role/{id}")
    public Result<List<UmsRole>> getRoleById(@PathVariable Long id){
        //查询指定对象和角色的对应关系
        LambdaQueryWrapper<UmsAdminRoleRelation> adminRoleLqw = new LambdaQueryWrapper<>();
        adminRoleLqw.eq(UmsAdminRoleRelation::getAdminId,id);
        List<UmsAdminRoleRelation> adminRoleRelations = umsAdminRoleRelationService.list(adminRoleLqw);
        //获得指定对象的角色
        List<UmsRole> roleList = adminRoleRelations.stream().map(adminRoleRelation -> {
            LambdaQueryWrapper<UmsRole> lqw = new LambdaQueryWrapper<>();
            lqw.eq(UmsRole::getId, adminRoleRelation.getRoleId());
            return umsRoleService.getOne(lqw);
        }).collect(Collectors.toList());
        return Result.success(roleList);
    }

    /**
     * 修改指定用户的账号状态
     */
    @PostMapping("/updateStatus/{id}")
    public Result<String> updateStatus(@PathVariable Long id,Integer status){
        //通过id查找用户
        UmsAdmin admin = umsAdminService.getById(id);
        admin.setStatus(status);
        //修改用户数据
        umsAdminService.updateById(admin);
        return Result.success();
    }

    /**
     * 给用户分配角色
     */
    @PostMapping("/role/update")
    public Result<String> roleUpdate(AdminRoleDto adminRoleDto){
        log.info(adminRoleDto.toString());
        //清空该用户的角色
        LambdaQueryWrapper<UmsAdminRoleRelation> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UmsAdminRoleRelation::getAdminId,adminRoleDto.getAdminId());
        umsAdminRoleRelationService.remove(lqw);
        //向用户关系表中添加数据
        Long adminId = adminRoleDto.getAdminId();
        List<UmsAdminRoleRelation> adminRoleRelations = adminRoleDto.getRoleIds().stream().map(role -> {
            UmsAdminRoleRelation umsAdminRoleRelation = new UmsAdminRoleRelation();
            umsAdminRoleRelation.setAdminId(adminId);
            umsAdminRoleRelation.setRoleId(role);
            return umsAdminRoleRelation;
        }).collect(Collectors.toList());
        //将数据批量插入
        umsAdminRoleRelationService.saveBatch(adminRoleRelations);
        return Result.success();
    }

    /**
     * 修改指定用户密码
     */
    @PostMapping("/updatePassword")
    public Result<String> updatePassword(@RequestBody Map map){
        return null;
    }
}
